/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mylibrary.player.util;

import ohos.agp.components.AttrSet;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;

import com.mylibrary.player.constant.Constants;

import java.io.IOException;
import java.util.Locale;
import java.util.Optional;

/**
 * Common util
 *
 * @since 2021-04-04
 */
public class CommonUtils {
    private static final String TAG = CommonUtils.class.getSimpleName();

    private static final int ONE_SECONDS_MS = 1000;
    private static final int ONE_MINS_MINUTES = 60;
    private static final int NUMBER = 16;
    private static final String TIME_FORMAT = "%02d";
    private static final String SEMICOLON = ":";
    /**
     * NO_NETWORK
     */
    public static final int NO_NETWORK = 0;
    /**
     * NETWORK_CLOSED
     */
    public static final int NETWORK_CLOSED = 1;
    /**
     * NETWORK_ETHERNET
     */
    public static final int NETWORK_ETHERNET = 2;
    /**
     * NETWORK_WIFI
     */
    public static final int NETWORK_WIFI = 3;
    /**
     * NETWORK_MOBILE
     */
    public static final int NETWORK_MOBILE = 4;
    /**
     * NETWORK_UNKNOWN
     */
    public static final int NETWORK_UNKNOWN = -1;

    private CommonUtils() {
    }

    /**
     * conversion of msToString
     *
     * @param ms ms
     * @return string
     */
    public static String msToString(int ms) {
        StringBuilder sb = new StringBuilder(NUMBER);
        int seconds = ms / ONE_SECONDS_MS;
        int minutes = seconds / ONE_MINS_MINUTES;
        if (minutes > ONE_MINS_MINUTES) {
            if (minutes > 0) {
                sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes / ONE_MINS_MINUTES));
                sb.append(SEMICOLON);
            }
            sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes % ONE_MINS_MINUTES));
            sb.append(SEMICOLON);
        } else {
            sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, minutes));
            sb.append(SEMICOLON);
        }
        if (seconds > minutes * ONE_MINS_MINUTES) {
            sb.append(String.format(Locale.ENGLISH, TIME_FORMAT, seconds - minutes * ONE_MINS_MINUTES));
        } else {
            sb.append("00");
        }
        return sb.toString();
    }

    /**
     * 通过资源ID获取颜色
     *
     * @param context comtext
     * @param resourceId id
     * @return int
     */
    public static int getColor(Context context, int resourceId) {
        try {
            return context.getResourceManager().getElement(resourceId).getColor();
        } catch (IOException | NotExistException | WrongTypeException e) {
            LogUtil.error(TAG, e.getMessage());
        }
        return Constants.NUMBER_NEGATIVE_1;
    }

    /**
     * 判断当前网络类型
     *
     * @param context context
     * @return return
     */
    public static int getNetworkType(Context context) {
        NetManager connectMgr = NetManager.getInstance(context);
        if (connectMgr == null) {
            return NO_NETWORK;
        }
        if (!connectMgr.hasDefaultNet()) {
            // 没有任何网络
            return NO_NETWORK;
        }
        NetHandle networkInfo = connectMgr.getDefaultNet(); // 获取默认的激活网络
        if (networkInfo == null) {
            // 网络断开或关闭
            return NETWORK_CLOSED;
        }
        NetCapabilities netCapabilities = connectMgr.getNetCapabilities(networkInfo); // 可以获取到NetHandle的对象
        // 表示有网NET_CAPABILITY_VALIDATED能用
        if (netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (netCapabilities.hasCap(NetCapabilities.BEARER_ETHERNET)) {
                // 以太网网络
                return NETWORK_ETHERNET;
            } else if (netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI)
                || netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE)) {
                // wifi网络，当激活时，默认情况下，所有的数据流量将使用此连接
                return NETWORK_WIFI;
            } else if (netCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR)) {
                // 移动数据连接,不能与连接共存,如果wifi打开，则自动关闭
                return NETWORK_MOBILE;
            }
        }
        return NETWORK_UNKNOWN; // 未知网络
    }

    /**
     * getScreenHeight
     *
     * @param context context
     * @return Screen Height
     */
    public static int getScreenHeight(Context context) {
        DisplayManager displayManager = DisplayManager.getInstance();
        Optional<Display> optDisplay = displayManager.getDefaultDisplay(context);
        Point point = new Point(0, 0);
        if (!optDisplay.isPresent()) {
            return (int) point.position[1];
        } else {
            Display display = optDisplay.get();
            display.getSize(point);
            return (int) point.position[1];
        }
    }

    /**
     * getScreenWidth
     *
     * @param context context
     * @return Screen Width
     */
    public static int getScreenWidth(Context context) {
        DisplayManager displayManager = DisplayManager.getInstance();
        Optional<Display> optDisplay = displayManager.getDefaultDisplay(context);
        Point point = new Point(0, 0);
        if (!optDisplay.isPresent()) {
            return (int) point.position[0];
        } else {
            Display display = optDisplay.get();
            display.getSize(point);
            return (int) point.position[0];
        }
    }

    /**
     * 获取自定义属性是布尔值
     *
     * @param attrSet
     * @param key 自定义属性名称
     * @param defValue 默认值
     * @return xml配置值
     */

    public static Boolean getBooleanValue(AttrSet attrSet, String key, boolean defValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getBoolValue();
        } else {
            return defValue;
        }
    }
}
